package com.itheima.health.job;

import com.itheima.health.common.RedisConst;
import com.itheima.health.service.SetMealService;
import com.itheima.health.util.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author ：李帅
 * @date ：Created in 2022年06月10日
 * @description ：清除照片
 * @version: 1.0
 */
@Component
@Slf4j
public class ClearImageJob {
    // 清理前需要等待的等待时间 最长等待设定为十分钟
    private static final Long MIN_DELETE_WAIT_TIME = 10*60 * 1000L;
    @Autowired
    private SetMealService setMealService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private QiniuUtils qiniuUtils;

    @Scheduled(cron = "0 0 1 * * ?")//凌晨一点清理
    public void executeInternal() throws JobExecutionException {
        log.info("开始清理图片");
        //查询redis缓存的照片名字
        BoundSetOperations boundSetOperations1 = redisTemplate.boundSetOps(RedisConst.SETMEAL_PICTURE_NAME);
        Set<String> set = boundSetOperations1.members();
        for (String img : set) {
            try {
                System.out.println("截取图片:"+img);
                Long createTime = Long.valueOf(img.split("_", 2)[0]);
                System.out.println(createTime);
                //判断等待时间是否大于清理前的最小等待时间；防止用户表单未提交，图片就被删除了
                if (System.currentTimeMillis() - createTime < MIN_DELETE_WAIT_TIME) {
                    log.info("等待时间小于设定的最小等待时间 不能被清理", img);
                    continue;
                }
                //判断是否被使用
                long count = setMealService.countByImg(img);
                if (count == 0) {
                    // 如果未被使用，则从七牛云删除
                    qiniuUtils.deleteFileFromQiniu(img);
                } else {
                    log.info("图片已使用", img);
                }
                // 无论是否垃圾图片，都从redis移除
                BoundSetOperations boundSetOperations2 = redisTemplate.boundSetOps(RedisConst.SETMEAL_PICTURE_NAME);
                boundSetOperations2.remove(img);
            } catch (RuntimeException e) {
                log.error("清理图片失败:" + img, e);
                continue;
            }
        }
        log.info("清理图片完成");
    }
}
